package com.example.administrator.myview.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.administrator.myview.R;
import com.example.administrator.myview.util.DownPicUtil;
import com.example.administrator.myview.util.MyUtils;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * 安卓与js交互
 * Created by Administrator on 2017/11/11.
 */

public class WebViewActivity extends Activity {
    WebView webView;
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
        webView=(WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);//增加允许存储权限。
        webView.loadUrl("http://wxpay.wxutil.com/mch/pay/h5.v2.php");
        webView.setWebViewClient(new WebViewClient(){
            //重写此方法拦截点击事件 不跳转至其他浏览器
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(url == null) return false;
                //其他自定义的scheme  微信官方的支付功能测试
                try {
                    if(url.startsWith("weixin://wap/pay?")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }
                    else {
                        Map extraHeaders = new HashMap();
                        extraHeaders.put("Referer", "http://wxpay.wxutil.com");
                        view.loadUrl(url, extraHeaders);
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return false;
                }
                return true;
            }
        });
        // 长按点击事件
        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                saveImage();
                return true;
            }
        });

        BridgeWebView bridgeWebView = null;
        //
        bridgeWebView.registerHandler("", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

            }
        });


    }
    //这里是获取点击的图片元素 这是通过url下载之后保存到本地的
    void saveImage(){
        //获取webView点击元素
        final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
        // 如果是图片类型或者是带有图片链接的类型
        if(hitTestResult.getType()== WebView.HitTestResult.IMAGE_TYPE||
                hitTestResult.getType()== WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE){
            // 弹出保存图片的对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("保存图片到本地");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    String url = hitTestResult.getExtra();
                    // 下载图片到本地
                    MyUtils.showToast(WebViewActivity.this,"是否保存");
                    DownPicUtil.downPic(url, new DownPicUtil.DownFinishListener(){

                        @Override
                        public void getDownPath(String s) {
                            Toast.makeText(WebViewActivity.this,"下载完成",Toast.LENGTH_LONG).show();
                            Message msg = Message.obtain();
                            msg.obj=s;
                            handler.sendMessage(msg);
                        }
                    });

                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                // 自动dismiss
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String picFile = (String) msg.obj;
            String[] split = picFile.split("/");
            String fileName = split[split.length-1];
            try {
                MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), picFile, fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + picFile)));
            Toast.makeText(WebViewActivity.this,"图片保存图库成功",Toast.LENGTH_LONG).show();
        }
    };



    //处理webView的点击回退事件 拦截系统返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
